
#include "PipelineLogger.h"

using namespace ttg;
using namespace ttg::extras;
using namespace ttg::services;
using namespace ttg::pipeline;

#ifdef TTG_PL_VISUALIZER

//----------------
//--- PLLogger ---
//----------------

PipelineLogger::PipelineLogger(const char *filename)
{
	this->info = NULL;
	this->xml = NULL;
	ServiceBase::_PublisherBase().subscribeAsSoonAsPossible("PIPELINE_UPDATE", this, processPipelineUpdate);
	ServiceBase::_PublisherBase().subscribeAsSoonAsPossible("ON_EXIT", this, processOnExit);
	/*this->isSubscribed_Update = ServiceBase::_PublisherBase()
									.subscribe("PIPELINE_UPDATE", this, processPipelineUpdate);
	this->isSubscribed_OnExit = ServiceBase::_PublisherBase()
									.subscribe("ON_EXIT", this, processOnExit);*/
	if (filename != NULL)
	{
		try
		{
			this->xml = new TTGXMLTree();
			xml->assign(XMLTree::XML_WO, filename);
			xml->addSectionAndOpen("Log");
		}
		catch (Error &err)
		{
			Logger::getRef()->addError(err);
			SAFE_DELETE(xml);
		}
	}
}

bool PipelineLogger::subsrcibe()
{
	if (!isSubscribed_Update)
		isSubscribed_Update = ServiceBase::_PublisherBase()
									.subscribe("PIPELINE_UPDATE", this, processPipelineUpdate);
	if (!isSubscribed_OnExit)
		isSubscribed_OnExit = ServiceBase::_PublisherBase()
									.subscribe("ON_EXIT", this, processOnExit);
	return isSubscribed_Update && isSubscribed_OnExit;
}

void PipelineLogger::close()
{
	if (xml != NULL)
	{
		xml->closeSection();
		xml->close();
		SAFE_DELETE(xml);
	}
}

void PipelineLogger::processPipelineUpdate(Subscriber *s, ttg::services::Event *ev)
{
	PipelineLogger *logger = dynamic_cast<PipelineLogger *>(s);
	ttg_internal::pipeline::PipelineInfo *info = dynamic_cast<ttg_internal::pipeline::PipelineInfo *>(ev);
	if (logger == NULL || info == NULL)
		addLocalError("PipelineLogger", "processPipelineUpdate", "Cannot cast");
	else
	{
		logger->info = info;
		if (logger->xml != NULL)
		{
			ttg_internal::pipeline::PipelineInfo::store(logger->xml->getSubXMLTree(), info);
		}
	}
}

void PipelineLogger::processOnExit(Subscriber *s, ttg::services::Event *ev)
{
	PipelineLogger *logger = dynamic_cast<PipelineLogger *>(s);
	if (logger == NULL)
		addLocalError("PipelineLogger", "processPipelineUpdate", "Cannot cast");
	else
	{
		logger->close();
	}
}

#endif
